<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="list"
          :dafault-sort="{ prop: 'timeOfEntry', order: 'ascending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{ row }">
              <img :src="row.staffPhoto" alt="" style="width: 100%">
            </template>
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignroles(row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="reset">
        <empDialog
          ref="addEmployees"
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        v-if="roleShowDialog"
        :visible.sync="roleShowDialog"
        title="分配角色"
      >
        <assignRole
          :id="curId"
          @success="hAssignRoleSuccess"
          @close="roleShowDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import empDialog from './empDialog'
import assignRole from './assignRole'
const hireType = {}
EmployeesEnum.hireType.forEach((item) => {
  hireType[item.id] = item.value
})

// const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
//   acc[item.id] = item.value
//   return acc
// }, {})

export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 3,
      list: [],
      // hireType: EmployeesEnum.hireType,
      total: 0,
      showDialog: false,
      roleShowDialog: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRoleSuccess() {
      // 关闭分配角色的弹层
      this.roleShowDialog = false
    },
    hAssignroles(id) {
      this.curId = id
      this.roleShowDialog = true
    },
    formData(list) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const one = list[0]
      if (!one) return
      const header = Object.keys(one).map((enkey) => {
        return map[enkey]
      })

      const data = list.map((item) => {
        const key = item.formOfEmployment
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      return { header, data }
    },
    // 导入功能的关键代码

    // 思路
    // - 1  发送请求获取数据
    // - 2. 将获取到数据进行格式化处理，处理成生成excel文件需要的格式的数据（将英文转中文）
    // - 3. 调用admin中关键的函数export_json_to_excel，生成excel文件
    async handleDownload() {
      // - 1  发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res.data.rows, 'res.data.rows') // 从后台获取到的数据
        const { header, data } = this.formData(res.data.rows)

        // - 2. 将获取到数据进行格式化处理，处理成生成excel文件需要的格式的数据（将英文转中文）
        //  - header: ['中文的表头']
        //  - data: [['一条数据的值'],[]]
        // - 3. 调用admin中关键的函数export_json_to_excel，生成excel文件

        //  import('@/vendor/Export2Excel')  懒加载的方式导入一个模块（文件）返回值是一个promise实例
        import('@/vendor/Export2Excel').then((excel) => {
          // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename, // 文件名
            autoWidth: this.autoWidth, // 自动适配宽度
            bookType: this.bookType // 文件的类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },

    hDel(id) {
      this.$confirm('确认删除该员工吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delEmployee(id)
          if (this.list.length === 0) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    reset() {
      this.$refs.addEmployees.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      //  重新渲染
      this.loadEmployees()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    formOfEmploymentFormat(data) {
      // return this.hireType.find((item) => item.id === data).value
      return hireType[data] || '未知'
    },
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log('获取员工列表', res)
        // 保存数据
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log('error', err)
      }
    }
  }
}
</script>
